<template>
    <div style="display: flex;justify-content: space-between;">
        <a-form size="small" :model="pageData" layout="inline" style="margin-bottom: 10px;" ref="formRef">
            <a-form-item label="月份">
                <a-month-picker class="bacClass" v-model="pageData.planMonthBegin" style="width:200px" />至
                <a-month-picker class="bacClass" v-model="pageData.planMonthEnd" style="width:200px" />
            </a-form-item>
            <a-form-item label="公司">
                <a-select class="bacClass" v-model="pageData.companyNames" style="width:200px" allow-clear multiple
                    :max-tag-count="1">
                    <a-option>织造一厂</a-option>
                    <a-option>织造二厂</a-option>
                    <a-option>织造三厂</a-option>
                    <a-option>织造四厂</a-option>
                </a-select>
            </a-form-item>
            <a-form-item label="报警值">
                <a-input-number class="bacClass" style="width:200px" v-model="pageData.alarmValue" :min="0"
                    :precision="1" />
            </a-form-item>
        </a-form>
        <Toolbar :items="['查询', '导出']" @select="doRefresh" @export="exportExcel"></Toolbar>
    </div>
    <div class="cssTable">
        <a-spin :loading="pageData.pageLoading" tip="加载中" dot
            style="height:100%;width: 98.5%;z-index:999 ;margin-left: 13px;">
            <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                :style="{ height: pageData.rHeight - 500 + 'px' }" :suppressDragLeaveHidesColumns="true"
                rowSelection="multiple" @grid-ready="gridReady" :defaultColDef="defaultColDef" class='ag-theme-alpine'
                :rowData="pageData.tableList" :columnDefs="pageData.filterColumns" :localeText="localeText1"></AgGridVuesCopys>
        </a-spin>

        <div class="graphics">
            <div ref="columnChart" class="columnChart"></div>
        </div>
    </div>
</template>

<script lang='ts' setup>
import { reactive, toRefs, ref, onMounted, Ref } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { post, get } from '@/api/http'
import { Message, Modal } from '@arco-design/web-vue'

import { localeText } from '@/api/aggridZw'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'
import { FormInstance } from "@arco-design/web-vue/es/form";
import { assTable } from '@/utils/assemblyLevelTable'
import * as echarts from 'echarts';

const localeText1: any = ref(localeText)
const pageData: any = reactive({
    pageLoading: false,
    rHeight: 0,
    tableList: [],
    reportData: [],
    companyNames: [],
    planMonthBegin: '',
    planMonthEnd: '',
    filterName: '',
    filterColumns: [],
    alarmValue: '',
})

const defaultColDef: any = {
    sortable: true,
    resizable: true,
    filter: true,
    flex: 1
}

const gridOption = ref()
const colState = ref()
const gridReady = (params: any) => {
    gridOption.value = params.api
    colState.value = params.columnApi
}
const tableColumns: any = [
    {
        headerName: '检查名称', field: 'planName',
        children: [
            { headerName: '', field: 'planName', },
        ],
    },
    {
        headerName: '织造一厂',
        children: [
            {
                headerName: '合格率', field: 'qualifiedRate1',
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > pageData.alarmValue) {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造二厂',
        children: [
            {
                headerName: '合格率', field: 'qualifiedRate2',
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > pageData.alarmValue) {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造三厂',
        children: [
            {
                headerName: '合格率', field: 'qualifiedRate3',
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > pageData.alarmValue) {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造四厂',
        children: [
            {
                headerName: '合格率', field: 'qualifiedRate4',
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > pageData.alarmValue) {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
    {
        headerName: '织造中心',
        children: [
            {
                headerName: '合格率', field: 'totalQualifiedRate',
                cellRenderer: (params: any) => {
                    let val = (params.value * 100).toFixed(1)
                    if (val > pageData.alarmValue) {
                        return "<span>" + val + "%" + "</span>";
                    } else {
                        return "<span style='color:red;font-weight: bold;'>" + val + "%" + "</span>";
                    }
                },
            },
        ],
    },
]

//根据公司下拉筛选数据
const filteredTableColumns = () => {
    if (pageData.companyNames.length === 0 || pageData.companyNames == null) {
        pageData.filterColumns = tableColumns;
    } else {
        pageData.filterColumns = tableColumns.map((column: any) => {
            if (column.headerName === '检查名称' || column.headerName === '织造中心') {
                return column;
            } else {
                // 检查列的 headerName 是否在 pageData.companyNames 中
                const isCompanyIncluded = pageData.companyNames.includes(column.headerName);
                if (isCompanyIncluded) {
                    // 如果包含，请返回整个列，包括子列
                    return column;
                } else {
                    // 如果未包含，则为null
                    return null;
                }
            }
        }).filter((column: any) => column !== null);
    }
}

//查询
const formRef = ref<FormInstance>();
function doRefresh() {
    filteredTableColumns()
    formRef.value?.validate().then((err: any) => {
        if (!err) {
            pageData.pageLoading = true
            post({
                url: "/qms/inspectionPlanResult/buildInspectionTotalReport",
                data: {
                    planMonthBegin: pageData.planMonthBegin,
                    planMonthEnd: pageData.planMonthEnd,
                    companyNames: pageData.companyNames,
                    planType: 1
                }
            })
                .then((res: any) => {
                    if (res.code === 200) {
                        pageData.tableList = res.data
                        gridOption.value.setRowData(res.data)
                        getEcharts()
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }
    })
}

// 导出
const exportExcel = async () => {
    // 确保数据加载完成
    await doRefresh();

    let nowRow = pageData.tableList.map((row: any) => {
        Object.keys(row).forEach(key => {
            if (row[key] === null || row[key] === undefined || row[key] === 0) {
                row[key] = '0';
            }
        });
        row['totalQualifiedRate'] = parseFloat((Number(row['totalQualifiedRate']) * 100).toFixed(1)) + '%';
        row['qualifiedRate4'] = parseFloat((Number(row['qualifiedRate4']) * 100).toFixed(1)) + '%';
        row['qualifiedRate3'] = parseFloat((Number(row['qualifiedRate3']) * 100).toFixed(1)) + '%';
        row['qualifiedRate2'] = parseFloat((Number(row['qualifiedRate2']) * 100).toFixed(1)) + '%';
        row['qualifiedRate1'] = parseFloat((Number(row['qualifiedRate1']) * 100).toFixed(1)) + '%';
        return row;
    });

    // 确保导出的时机与表格渲染时机一致
    await assTable(tableColumns, nowRow, '检查名称按厂区统计报表');
}

//柱形图
const columnChart = ref<any>()
let myChart: any = null
const getEcharts = () => {
    pageData.tableList.map((o: any) => {
        let name = o.planName.replace('年', '-')
        o.planName = name.replace('半月', '');
    })
    let data: any = []
    if (pageData.companyNames.length === 0 || pageData.companyNames == null) {
        data = ['一厂', '二厂', '三厂', '四厂', '织造中心']
    } else {
        data = pageData.companyNames.map((o: any) => o.replace('织造', ''))
        data.push('织造中心');
    }
    let echartData = data.filter((o: any) => o != '织造中心')
    const series = echartData.map((title: any) => {
        let rate = ''
        let color = '';
        if (title == '一厂') {
            rate = 'qualifiedRate1'
            color = '#2561ec';
        } else if (title == '二厂') {
            rate = 'qualifiedRate2'
            color = '#ed8523';
        } else if (title == '三厂') {
            rate = 'qualifiedRate3'
            color = '#8f8c88';
        } else if (title == '四厂') {
            rate = 'qualifiedRate4'
            color = '#25f3e8';
        }
        return {
            name: title,
            type: 'bar',
            data: pageData.tableList.map((res: any) => (res[rate] * 100).toFixed(1)).filter((o: any) => o != null),
            label: {
                show: true,
                position: 'top',
                formatter: (params: any) => {
                    return params.value + '%';
                },
            },
            tooltip: {
                valueFormatter: (value: any) => value + '%',
            },
            itemStyle: {
                color: color,
            },
        };
    });
    let option = {
        title: {
            text: '',
            subtext: ''
        },
        tooltip: {
            trigger: 'axis',
        },
        legend: {
            data: data,
        },
        toolbox: {
            show: true,
            feature: {
                magicType: { show: true, type: ['line', 'bar'] },
                saveAsImage: { show: true }
            }
        },
        calculable: true,
        xAxis: [
            {
                type: 'category',
                data: pageData.tableList.map((res: any) => res.planName),
            }
        ],
        yAxis: [
            {
                type: 'value',
                axisLabel: {
                    formatter: '{value}.0%'
                },
            }
        ],
        series: series
    };
    option && myChart.setOption(option, true);
}

onMounted(() => {
    pageData.rHeight = document.getElementsByClassName("main-section")[0]?.clientHeight
    //弹出层的高
    if (pageData.rHeight !== undefined) {
        pageData.rHeight = pageData.rHeight;
    }
    pageData.alarmValue = 80
    doRefresh()
    myChart = echarts.init(columnChart.value);
})
</script>

<style lang='less' scoped>
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
    user-select: initial;
    -moz-user-select: text;
    -ms-user-select: text;
    -webkit-user-select: text;
}

:deep(.arco-table-td-content) {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
}

:deep(.arco-select-view-multiple.arco-select-view-disabled .arco-select-view-tag) {
    color: #4e5969 !important;
    ;
    background-color: white;
    border-color: white;
    font-size: 14px
}


.graphics {
    width: 97%;
    height: 49%;
    position: absolute;
    box-sizing: border-box;
    display: flex;
    margin-top: 10px;
}

.columnChart {
    width: 100%;
    height: 100%;
    z-index: 100;

}
</style>